import type { AuthPermission, AuthPermissionTransferItem } from '@/pages/Auth/AuthRole/data';
import {
  fetchConfigurableAuthPermission,
  queryAdminRoleAccessList,
} from '@/pages/Auth/AuthRole/service';
import { Transfer } from 'antd';
import React, { useEffect, useState } from 'react';

export interface AuthPermissionConfigurationProps<T> {
  id?: string;
  sourceValue?: AuthPermission[];
  defaultValue?: AuthPermission[];
  visible?: boolean;
  onChange?: (targetTransferItems: T[]) => void;
  onCancel?: (e: React.MouseEvent<HTMLElement>) => void;
  onClose?: () => void;
}

const AuthPermissionConfiguration: React.FC<AuthPermissionConfigurationProps<AuthPermission>> = (
  params: AuthPermissionConfigurationProps<AuthPermission>,
) => {
  const [targetKeys, setTargetKeys] = useState<string[]>(getTargetKeys(params.defaultValue));
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [items, setItems] = useState<AuthPermissionTransferItem[]>(
    params.sourceValue?.flatMap((item) => transferAdminAccess2TransferItem(item)) || [],
  );

  function getTargetKeys(permissions?: AuthPermission[]): string[] {
    if (permissions) {
      const data = permissions.flatMap((item) => transferAdminAccess2TransferItem(item));
      return data?.map((item) => item.key || item.code || '');
    }
    return [];
  }

  function transferAdminAccess2TransferItem(item: AuthPermission): AuthPermissionTransferItem {
    return {
      key: String(item.id),
      title: item.name,
      description: item.name,
      disabled: false,
      ...item,
    };
  }

  function reverseAdminAccess2TransferItem(item: AuthPermissionTransferItem): AuthPermission {
    return {
      id: item.id,
      name: item.name,
    };
  }

  // 加载全部可选角色
  useEffect(() => {
    fetchConfigurableAuthPermission({}).then((res) => {
      const data = res.data?.flatMap((item) => transferAdminAccess2TransferItem(item)) || [];

      setItems(data);
    });
  }, []);

  // 加载已选择角色
  useEffect(() => {
    if (params.id && params.defaultValue == undefined) {
      queryAdminRoleAccessList({ roleId: params.id }).then((res) => {
        const data = res.data.flatMap((item) => transferAdminAccess2TransferItem(item));
        const fetchTargetKeys = data?.map((item) => `${item.key}` || '');
        setTargetKeys(fetchTargetKeys);
      });
    }
  }, [params.id]);

  // eslint-disable-next-line no-shadow
  const handleChange = (targets: string[], direction: string, moveKeys: string[]) => {
    if (direction === 'right') {
      setTargetKeys([...targets, ...moveKeys]);
    }

    if (direction === 'left') {
      const keys = targets.filter((o) => !moveKeys.includes(o));
      setTargetKeys(keys);
    }

    if (params.onChange) {
      const targetAdminRoles = items.filter((o) => targets.includes(o.key || ''));
      const adminRoleItems = targetAdminRoles.map((o) => reverseAdminAccess2TransferItem(o));
      params.onChange(adminRoleItems);
    }
  };

  return (
    <Transfer
      showSearch
      dataSource={items}
      // style={{height: '500px'}}
      listStyle={{ height: '450px', width: '100%' }}
      titles={['可分配', '已分配']}
      targetKeys={targetKeys}
      onChange={handleChange}
      selectedKeys={selectedKeys}
      onSelectChange={(sourceSelectedKeys, targetSelectedKeys) => {
        setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
      }}
      render={(item) => (item.title ? item.title : '')}
    />
  );
};
export default AuthPermissionConfiguration;
